package com.shit.springmvc.controller;

import lombok.Data;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class Main {
    @RequestMapping(value = "/getname", method = RequestMethod.GET)
    public String getName() {
        return "hello MVC";
    }

    @GetMapping("getage")
    public String getAge(Integer age) {
        return String.valueOf(age);
    }

    @Data // 会为 Student 这个类加上 getter, setter, toString 等方法
    public static class Student {
        private String name;
        private int age;
        private String sex;
    }

    @RequestMapping("/form")
    public Student getJson(Student student) {
        System.out.println(student.getAge() + 8);
        return student;
    }

    @RequestMapping("/download")       // 前端上传的文件名为 photo
    public String download(@RequestPart("photo")MultipartFile multipartFile) throws IOException {
        File file = new File("D:/beauty.jpg"); // 将这个文件放在 D 盘上, 并起名为 beauty.jpg
        multipartFile.transferTo(file);
        return "下载文件完成";
    }

    @RequestMapping("/cookietest")
    public String cookieTest(@CookieValue(value = "who", required = false)String value) {
        return value;
    }

    @RequestMapping("setsession")
    public String setSessiont(HttpServletRequest req) {
        // 设置一下会话
        HttpSession session = req.getSession(true); // 设置为 True，如果不存在会话，那就创建一个会话
        if (session != null) { // 没有创建会话，那就设置一下属性
            session.setAttribute("who", "pig");
        }
        return "会话设置成功";
    }

    @RequestMapping("sessiontest")
    public String sessionTest(@SessionAttribute("who")String value) {
        return value;
    }

    @RequestMapping("rename")
    public String rename(@RequestParam(value = "p", required = false)String place, @RequestParam(value = "a")String a) {
        return "place 为" + place + "<br>" + a;
    }
}
